package server;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import action.Action;
import action.ActionConnect;
import action.ActionMove;

//move#x#y##
public class Parser {
	
	public static final String BUTTON_DOWN_SX = "sxdown";
	public static final String BUTTON_DOWN_DX = "dxdown";
	public static final String BUTTON_UP_SX = "sxup";
	public static final String BUTTON_UP_DX = "dxup";
	public static final String MOVE = "move";
	public static final String START_CONNECTION = "connect";
	private Action actionLeftClickUp;
	private Action actionLeftClickDown;
	private Action actionRightClickUp;
	private Action actionRightClickDown;
	private Action actionMove;
	private Action actionConnect;
	private Action doNothing;
	

	public Parser(Action actionLeftClickUp, Action actionLeftClickDown,Action actionRightClickUp, Action actionRightClickDown,Action actionMove, Action doNothing, Action actionConnect) {
		super();
		this.actionLeftClickUp = actionLeftClickUp;
		this.actionLeftClickDown = actionLeftClickDown;
		this.actionRightClickUp = actionRightClickUp;
		this.actionRightClickDown = actionRightClickDown;
		this.actionMove = actionMove;
		this.doNothing=doNothing;
		this.actionConnect = actionConnect;
	}

	public Action match(String mex){
		String command;
		mex=mex.replace("##", "");
		int x,y;
		boolean match = false;
		Action action = doNothing;
		String regex = "(.*)#(.*)#(.*)";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher;
		matcher = pattern.matcher(mex);// mi pare che qst oggetti sono usa e getta!
		match = matcher.find();
		if(match){
			command = matcher.group(1);
			x = (Integer.parseInt(matcher.group(2)));
			y = (Integer.parseInt(matcher.group(3)));
			if(command.compareTo(BUTTON_DOWN_SX)==0)
				action = actionLeftClickDown;
			else if(command.compareTo(BUTTON_DOWN_DX)==0)
				action = actionRightClickDown;
			else if(command.compareTo(BUTTON_UP_SX)==0)
				action = actionLeftClickUp;
			else if(command.compareTo(BUTTON_UP_DX)==0)
				action = actionRightClickUp;
			else if(command.compareTo(MOVE)==0){
				action = actionMove;
				ActionMove a = (ActionMove)action;
				a.setX(x);
				a.setY(y);
			}else if(command.compareTo(START_CONNECTION)==0){
				action = actionConnect;
				ActionConnect a = (ActionConnect)action;
				a.setDpi(x);
				a.setDestinationPort(y);
			}
		}
		return action;
	}

}
